package com.edu.whty.common.tools;

import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Json转换工具类
 *
 * @date 2014年11月27日
 */
public class JsonUtils {

    private static ObjectMapper mapper;

    private Logger logger = LoggerFactory.getLogger(getClass());

    private static synchronized ObjectMapper getMapperInstance() {
        if (mapper == null) {
            mapper = new ObjectMapper();
            mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }
        return mapper;
    }

    /**
     * 将json字符串转换为java对象
     *
     * @param json
     * @param clazz
     * @return
     */
    public static Object jsonToObj(String json, Class<?> clazz) {
        Object obj = null;
        try {
            ObjectMapper objectMapper = getMapperInstance();
            obj = objectMapper.readValue(json, clazz);
        } catch (Exception e) {
//			logger.error(json);
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 将java对象转换成json字符串
     *
     * @param obj
     * @return
     */
    public static String ojbTojson(Object obj) {
        String json = "";
        try {
            ObjectMapper objectMapper = getMapperInstance();
            json = objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }


}
